package com.hankol.community

import android.annotation.SuppressLint
import android.os.Handler
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.baselibrary.Constants
import com.baselibrary.MessageBus
import com.baselibrary.activity.BaseActivity
import com.baselibrary.bean.DynamicInfoData
import com.baselibrary.bean.FriendListBean
import com.baselibrary.bean.SelectSendFriend4Bean
import com.baselibrary.extension.checkNotNull
import com.baselibrary.extension.checkValue
import com.baselibrary.manager.RecycleViewManager
import com.baselibrary.router.ActivityRouter
import com.baselibrary.utils.*
import com.baselibrary.view.QuickIndexBar
import com.baselibrary.utils.EmptyViewUtil
import com.hankol.message.HKIMUtils
import com.hankol.community.adapter.SelectFriendAdapter
import com.hankol.community.bean.BatchUserBean
import com.hankol.community.databinding.ActivitySelectFriendShareBinding
import com.hankol.community.view.PinyinComparator
import com.hankol.community.viewmodel.SelectFriendViewModel
import io.rong.imlib.RongIMClient
import io.rong.imlib.model.Conversation
import java.util.*


/**分享至
 * @author: merbng
 * @time: 2022/5/27 17:18
 * @description:
 */
@Route(path = ActivityRouter.COMMUNITY.COMMUNITY_SELECTED_FRIEND)
class SelectFriendShareActivity : BaseActivity() {
    private lateinit var mDataBinding: ActivitySelectFriendShareBinding
    private lateinit var mViewModel: SelectFriendViewModel
    private lateinit var mAdapter: SelectFriendAdapter
    private lateinit var mAdapter2Head: SelectFriendAdapter
    private lateinit var tHandler: Handler
    private val HANDLER_CODE = 0x11
    val headView by lazy { LayoutInflater.from(applicationContext).inflate(R.layout.head_select_friend, null) }
    override fun getLayoutId(): Int {
        return R.layout.activity_select_friend_share
    }

    private var dynamicBean: SelectSendFriend4Bean? = null
    private var characterParserUtil: CharacterParserUtil? = null
    private var countryChangeUtil: GetCountryNameSort? = null
    override fun init() {
        if (intent.hasExtra("dynamic")) {
            dynamicBean = intent.getParcelableExtra<SelectSendFriend4Bean>("dynamic")!!
        }
        intent.extras?.let {
            if (ARouterUtils.parseParams(it, "dynamic")[0].checkNotNull()) {
                val jsonBean: String = ARouterUtils.parseParams(it, "dynamic")[0]
                dynamicBean = GsonUtils.parseJsonToBean(jsonBean, SelectSendFriend4Bean::class.java)
            }
        }

        mDataBinding = getDataBinding<ActivitySelectFriendShareBinding>()
        mViewModel = getActivityViewModelProvider(this).get(SelectFriendViewModel::class.java)
        tHandler = Handler(Handler.Callback {
            tHandler.postDelayed({
                mViewModel.reqSearchFriend(mDataBinding.edtSelectFriendContent.text.toString())
            }, 100)
            return@Callback false
        })

        mAdapter = SelectFriendAdapter()
        mAdapter2Head = SelectFriendAdapter()
        mDataBinding.rvSelectFriendList.adapter = mAdapter
        characterParserUtil = CharacterParserUtil()
        countryChangeUtil = GetCountryNameSort()
        mViewModel.reqFriendList()
        mViewModel.friendLiveData.observe(this, Observer<List<FriendListBean>> {
            try {
                RongIMClient.getInstance().getConversationListByPage(object : RongIMClient.ResultCallback<List<Conversation>>() {
                    @SuppressLint("NotifyDataSetChanged")
                    override fun onSuccess(conversationList: List<Conversation>?) {
                        if (conversationList.checkNotNull()) {
                            val ids = mutableListOf<String>()
                            for (conversation in conversationList!!) {
                                ids.add(conversation.targetId)
                            }
                            mViewModel.reqUidsGetUserInfo(CommonUtil.join(ids.toTypedArray(), ","))
                        }
                        //没有最近聊天
                        if (it.checkNotNull()) {
                            val finalList = mutableListOf<FriendListBean>()
                            for (bean in it) {
                                val sorftKey = characterParserUtil?.getSelling(bean.name)
                                val friendSingleBean = FriendListBean(bean.friendId, bean.name, bean.icon, sorftKey, bean.isFans)
                                var sortLetter = countryChangeUtil?.getSortLetterBySortKey(sorftKey)
                                if (sortLetter == null) {
                                    sortLetter = countryChangeUtil?.getSortLetterBySortKey(bean.name)
                                }
                                friendSingleBean.letter = sortLetter
                                finalList.add(friendSingleBean)
                            }
                            Collections.sort(finalList, PinyinComparator())
                            mAdapter.setNewData(finalList)
                        }
                    }

                    override fun onError(p0: RongIMClient.ErrorCode?) {
                    }
                }, 0, 5, Conversation.ConversationType.PRIVATE);
            } catch (e: Exception) {
            }

        })
        mViewModel.friendLd.observe(this, Observer {
            if (it.checkNotNull()) {
                mAdapter.removeAllHeaderView()
                mAdapter.setNewData(it)
            } else {
                mAdapter.setNewData(null)
                mAdapter.emptyView = EmptyViewUtil.getEmptyView(Constants.TYPE_FOLLOW_FANS_FRIEND, mDataBinding.rvSelectFriendList, "暂无搜索结果")
            }
        })
        mViewModel.userInfoListLd.observe(this, Observer {
            setLatelyData(it)
        })
        initListener()
        mDataBinding.tvSelectFriendCancel.setOnClickListener { finish() }
        mDataBinding.llSelectFriendOver.setOnClickListener {
            mDataBinding.llSelectFriendOver.visibility = View.GONE
            //点完成--弹窗
            val dialog = PopUtils.showBottomShareDialog(this, dynamicBean?.showType!!, if (dynamicBean?.images?.size == 0) dynamicBean?.cover.checkValue() else dynamicBean?.images!![0].checkValue(), selectFriendList, object : PopUtils.IBottomShareCallBack {
                override fun clickOk(str: String) {
                    //分别发送
                    val targetIds = mutableListOf<String>()
                    for (bean in selectFriendList) {
                        targetIds.add("${bean.friendId}")
                    }
                    val bean = DynamicInfoData()
                    bean.apply {
                        dynamicBean?.let {
                            id = it.id
                            type = it.showType
                            cover = if (type == Constants.DYNAMIC_TYPE_VIDEO) it.cover else it.images!![0].checkValue()
                            title = if (it.title.checkNotNull()) it.title.checkValue() else it.content.checkValue()
                            heardUrl = it.icon
                            nickName = it.name
                            isFans = it.isFans
                            path = it.route.checkValue()
                            liveState = it.liveState
                            sendMessage = str.checkValue()
                        }
                    }
                    HKIMUtils.sendMessage4DynamicCard(targetIds, bean)
                    HKToastUtils.showToast("分享成功")
                    EventBusUtils.sendNotify(MessageBus.msgId_share_success)
                    finish()
                }

                override fun clickCancel() {
                }
            })
            dialog.setOnDismissListener {
                //弹窗消失 显示 完成按钮
                mDataBinding.llSelectFriendOver.visibility = View.VISIBLE
            }
        }
    }

    private fun setLatelyData(ulist: List<BatchUserBean>?) {
        val rvLateChat = headView.findViewById<RecyclerView>(R.id.rv_late_chat)
        rvLateChat.adapter = mAdapter2Head
        val list = mutableListOf<FriendListBean>()
        ulist?.forEach {
            list.add(FriendListBean(it.id.toLong(), it.name.checkValue(), it.icon.checkValue(), "", it.isFans))
        }
        mAdapter2Head.setNewData(list)
        mAdapter2Head.setOnItemClickListener { _, _, position ->
            //最近聊天点击
            val friendListBean = mAdapter2Head.data as List<FriendListBean>
            val currentBean = friendListBean[position]
            mAdapter2Head.lastLetter = ""
            mAdapter2Head.mHashMap.clear()
            for (datum in mAdapter2Head.data) {
                if (datum.friendId == currentBean.friendId) {
                    currentBean.isSelected = !currentBean.isSelected
                }
            }
            for (datum in mAdapter.data) {
                if (datum.friendId == currentBean.friendId) {
                    datum.isSelected = currentBean.isSelected
                }
            }

            clickUser(currentBean)
            for (bean in selectFriendList) {
                currentBean.isSelected = bean.friendId == currentBean.friendId
            }
            if (selectFriendList.size == 0) {
                for (datum in mAdapter.data) {
                    if (datum.friendId == currentBean.friendId) {
                        currentBean.isSelected = !currentBean.isSelected
                    }
                }
                for (datum in mAdapter2Head.data) {
                    if (datum.friendId == currentBean.friendId) {
                        currentBean.isSelected = !currentBean.isSelected
                    }
                }
            }
            mAdapter.notifyDataSetChanged()
            mAdapter2Head.notifyDataSetChanged()
        }
        mAdapter.addHeaderView(headView)
        mDataBinding.rvSelectFriendList.postDelayed(Runnable {
            mDataBinding.rvSelectFriendList.scrollToPosition(0)
        }, 50)
    }

    var selectFriendList = mutableSetOf<FriendListBean>()

    @SuppressLint("NotifyDataSetChanged")
    fun initListener() {
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val friendListBean = mAdapter.data as List<FriendListBean>
            val currentBean = friendListBean[position]
            mAdapter.lastLetter = ""
            mAdapter.mHashMap.clear()
            for (datum in mAdapter.data) {
                if (datum.friendId == currentBean.friendId) {
                    currentBean.isSelected = !currentBean.isSelected
                }
            }
            for (datum in mAdapter2Head.data) {
                if (datum.friendId == currentBean.friendId) {
                    datum.isSelected = currentBean.isSelected
                }
            }
            clickUser(currentBean)
            for (bean in selectFriendList) {
                currentBean.isSelected = bean.friendId == currentBean.friendId
            }
            if (selectFriendList.size == 0) {
                for (datum in mAdapter2Head.data) {
                    if (datum.friendId == currentBean.friendId) {
                        currentBean.isSelected = !currentBean.isSelected
                    }
                }
                for (datum in mAdapter.data) {
                    if (datum.friendId == currentBean.friendId && selectFriendList.size != 0) {
                        currentBean.isSelected = !currentBean.isSelected
                    } else {
                        currentBean.isSelected = false
                    }
                }
            }
            mAdapter2Head.notifyDataSetChanged()
            mAdapter.notifyDataSetChanged()
        }
        mDataBinding.edtSelectFriendContent.setOnEditorActionListener { textView, i, keyEvent ->
            //隐藏软键盘
            @SuppressLint("WrongConstant") val imm = getSystemService("input_method") as InputMethodManager
            imm.toggleSoftInput(0, 2)
            tHandler.removeMessages(888)
            mViewModel.reqSearchFriend(mDataBinding.edtSelectFriendContent.text.toString())
            true
        }

        mDataBinding.edtSelectFriendContent.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
            }

            override fun afterTextChanged(p0: Editable?) {
                tHandler.removeMessages(HANDLER_CODE)
                tHandler.sendEmptyMessage(HANDLER_CODE)
            }

        })
        mDataBinding.qibSelectFriend.setOnIndexChangeListener(object : QuickIndexBar.OnIndexChangeListener {
            override fun onIndexChange(selectIndex: Int) {
                mDataBinding.tvSelectFriendQuickIndex.visibility = View.VISIBLE
                mDataBinding.tvSelectFriendQuickIndex.text = QuickIndexBar.INDEX_ARRAYS[selectIndex]
                if (mAdapter.mHashMap.containsKey(QuickIndexBar.INDEX_ARRAYS[selectIndex])) {
                    RecycleViewManager.smoothMoveToPosition1(mDataBinding.rvSelectFriendList, mAdapter.mHashMap.getValue(QuickIndexBar.INDEX_ARRAYS[selectIndex]))
                }
            }

            override fun onActionUp() {
                mDataBinding.tvSelectFriendQuickIndex.visibility = View.GONE
            }
        })
    }

    private fun clickUser(currentBean: FriendListBean) {
        //加入到底部弹窗
        if (currentBean.isSelected) {
            if (selectFriendList.size >= 9) {
                HKToastUtils.showToast("最多只能选择9个聊天")
                currentBean.isSelected = !currentBean.isSelected
                return
            }
        }

        if (currentBean.isSelected) {
            mViewModel.addSelectList(currentBean, selectFriendList)
        } else {
            mViewModel.removeSelectList(currentBean, selectFriendList)
        }
        mDataBinding.llSelectFriendOver.visibility = if (selectFriendList.size > 0) View.VISIBLE else View.GONE
        mDataBinding.tvSelectFriendCount.text = selectFriendList.size.toString()

    }
}